package bg.ittalents.homework.airport;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

public class FileLogger implements EventLogger {

	private static String DEFAULT_OUTPUT_FILENAME = "Example_Output.txt";

	private String outputFile;
	private PrintStream outputStream;

	public FileLogger() throws FileNotFoundException,
			UnsupportedEncodingException {
		
		this(DEFAULT_OUTPUT_FILENAME);
	}

	public FileLogger(String fileName) throws FileNotFoundException,
			UnsupportedEncodingException {

		if (fileName != null) {
			outputFile = fileName;
		} else {
			createDefaultFile();
		}
		
		createIfNotExist();
		outputStream = new PrintStream(outputFile, "UTF-8");
	}

	private void createIfNotExist() {
		File file = new File(outputFile);

		if (!file.exists()) {

			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void createDefaultFile() {
		this.outputFile = DEFAULT_OUTPUT_FILENAME;

	}

	@Override
	public void log(String data) throws IOException {

		outputStream.println(data);

	}

	@Override
	protected void finalize() throws Throwable {
		outputStream.close();
		super.finalize();
	}
}
